//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/3.
//  Copyright © 2015年 魏强. All rights reserved.

#import "KDWebBlockSetController.h"
#import "KDGetWebView.h"
#import "KDEditeCellModel.h"
#import "KDNoticeView.h"
#import "KDAddKeywordView.h"
#import "KDMainwordAddView.h"
#import "KDWebEditCell.h"
#import "KDWebSetCellModel.h"
#import "KDWebBlockEditController.h"
#import "findWebBloclListParam.h"
#import "findWebBloclListResult.h"
#import "KDMonitorRequestTool.h"
#import "KDMSettingCellModel.h"
#import "KDWebEditCellModel.h"
#import "KDDeleteWebBlockParam.h"
#import "KDDeleteWebBlockResult.h"
#import "SVProgressHUD.h"
#define AddKeyWordView_Height 44
#define REGIONVIEW_HEIGHT 75
#define CELL_HEIGHT 40
#define NOTICE_LINE_HEIGHT 21
@interface KDWebBlockSetController ()< KDAddKeywordViewDelegate,KDWebBlockEditControllerDelegate, KDWebEditCellDelegate, UITableViewDelegate, UITableViewDataSource>
/**
 *  控制器底部的scrollView
 */
@property (nonatomic, weak) UIScrollView *underScrollView;
@property (nonatomic, weak) KDAddKeywordView *webNameView;
@property (nonatomic, weak) KDAddKeywordView *webAddressView;
@property (nonatomic, strong) NSArray *infoArr;
@property (nonatomic, weak) UIButton *saveBtn;
@property (nonatomic, weak) KDNoticeView *noticeView1;
@property (nonatomic, weak) KDNoticeView *noticeView2;
@property (nonatomic, weak) UITableView *tableView;
/**
 *  第几页
 */
@property (nonatomic, copy) NSString * page;

@end

@implementation KDWebBlockSetController
- (NSArray *)infoArr{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
    self.title = @"网站板块设置";
    self.page = @"1";
    [self setUpNavBar];
    [self setUpScrollView];
    [self setUpWebNameView];
    [self setUpTableView];
//    [self getWebBlockListRequest];
    
}
#pragma mark - 板块设置区
- (void)setUpNavBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
}
/**
 *  设置控制器底部scrollView
 */
- (void)setUpScrollView{
    //加一个挡板
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    //初始化underScrollView
    UIScrollView *underScrollView = [[UIScrollView alloc]init];
    self.underScrollView = underScrollView;
    underScrollView.frame = CGRectMake(0, 0, screenW, screenH);
    
    underScrollView.backgroundColor = BackGroundColor;
    underScrollView.showsHorizontalScrollIndicator = NO;
    underScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.underScrollView];
}
/**
 *  设置板块名称
 */
- (void)setUpWebNameView{
    KDAddKeywordView *webNameView = [KDAddKeywordView addKeywordView];
    self.webNameView = webNameView;
    webNameView.delegate = self;
    webNameView.name = @"添加网站板块";
    webNameView.frame = CGRectMake(0, 10, screenW, AddKeyWordView_Height);
//    webNameView.chosen = YES;
    [self.underScrollView addSubview:webNameView];
    
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    self.noticeView1 =noticeView;
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(webNameView.frame), screenW, NOTICE_LINE_HEIGHT + 15);
    noticeView.title = @"请点击添加网站子板块！";
    [self.underScrollView addSubview:noticeView];
}

- (void)setUpTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , CGRectGetMaxY(self.webNameView.frame), screenW,  (self.infoArr.count+1) * CELL_HEIGHT) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.separatorColor = [UIColor whiteColor];
    [self.underScrollView addSubview:tableView];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getWebBlockListRequest)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreWebBlockListRequest)];
    self.tableView.footer = footer;
    [self.tableView.header beginRefreshing];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
}
#pragma mark - 网络请求区
/**
 *  获取网站列表的请求
 */
- (void)getWebBlockListRequest{
    WS(ws);
    self.page = @"1";
    findWebBloclListParam *param = [[findWebBloclListParam alloc]init];
    param.method = @"getMonitorWebSiteModuleList";
    param.p = self.page;
    param.limit = @"20";
    param.wsm_id = self.model.m_Id ;
    [KDMonitorRequestTool findWebBlocklListMonitorWithParam:param success:^(findWebBloclListResult *responseObejct) {
//        KDLog(@"%@", responseObejct);
        if ([responseObejct.status isEqualToString:@"ok"]) {
            if (responseObejct.webPageInfoList.count == 0) {//如果没有数据，就告诉他没有
                [SVProgressHUD showInfoWithStatus:@"没有相关子板块！" maskType:SVProgressHUDMaskTypeGradient];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"获取板块列表成功！" maskType:SVProgressHUDMaskTypeGradient];
                ws.infoArr = responseObejct.webPageInfoList;
                ws.tableView.height = CELL_HEIGHT * ws.infoArr.count;
                [ws.tableView reloadData];
//                KDLog(@"tableView.y=%f,\n tableView.height=%f ",ws.tableView.y, ws.tableView.height);

            }
        }
        [ws.tableView.header endRefreshing];
    } failure:^(NSError *error) {
        [ws.tableView.header endRefreshing];
        [SVProgressHUD showInfoWithStatus:@"获取板块列表失败，请检查网络！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@", error);
    }];
}
- (void)getMoreWebBlockListRequest{
    WS(ws);
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    findWebBloclListParam *param = [[findWebBloclListParam alloc]init];
    param.method = @"getMonitorWebSiteModuleList";
    param.p = self.page;
    param.limit = @"20";
    param.wsm_id = self.model.m_Id;
    [KDMonitorRequestTool findWebBlocklListMonitorWithParam:param success:^(findWebBloclListResult *responseObejct) {
//        KDLog(@"%@", responseObejct);
        if ([responseObejct.status isEqualToString:@"ok"]) {
            if (responseObejct.count == 0) {
                [ws.tableView.footer endRefreshing];
            }else{
                NSMutableArray *tempArr = [NSMutableArray arrayWithArray:ws.infoArr];
                [tempArr addObjectsFromArray:responseObejct.webPageInfoList];
                ws.infoArr = tempArr;
                ws.tableView.height = CELL_HEIGHT * ws.infoArr.count;
                [ws.tableView reloadData];
            }
        }
        [ws.tableView.footer endRefreshing];
    } failure:^(NSError *error) {
        [ws.tableView.footer endRefreshing];
        [SVProgressHUD showInfoWithStatus:@"获取板块列表失败，请检查网络！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@", error);
    }];
}
/**
 *  删除板块的请求
 */
- (void)deleteBlockRequestWithModel:(KDWebEditCellModel *)model{
    KDDeleteWebBlockParam *param = [[KDDeleteWebBlockParam alloc]init];
    param.ws_id = model.Id;
    param.method = @"delMonitorWebSiteModule";
    [KDMonitorRequestTool deleteWebBlockMonitorWithParam:param success:^(KDDeleteWebBlockResult *responseObejct) {
        if ([responseObejct.status isEqualToString:@"ok" ]) {
            if (responseObejct.info == 1) {
                NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
                [tempArr removeObjectAtIndex:model.index];
                self.infoArr = tempArr;
                [self.tableView reloadData];
                [SVProgressHUD showSuccessWithStatus:@"删除板块成功！" maskType:SVProgressHUDMaskTypeGradient];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"该板块已不存在！" maskType:SVProgressHUDMaskTypeGradient];
            }
        }
        
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
        [SVProgressHUD showErrorWithStatus:@"删除板块失败,请检查网络！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KDWebEditCell *cell = [KDWebEditCell cellWithTableView:tableView];
    cell.model = self.infoArr[indexPath.row];
    cell.model.index = indexPath.row;
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
#pragma mark - 事件点击区
/**
 *  返回按钮被点击了
 */
- (void)backViewClick{
    [self.navigationController popViewControllerAnimated:YES];
}

//- (void)loadData{
//    if (iOS7) {
//        UIAlertView *aletView = [[UIAlertView alloc]initWithTitle:@"保存成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [aletView show];
//    }else{
//        WS(ws);
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"保存成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            [ws.navigationController popViewControllerAnimated:YES];
//        }];
//        [alertController addAction:cancelAction];
//        [alertController addAction:okAction];
//        [self presentViewController:alertController animated:YES completion:nil];
//    }
    
//}

#pragma mark - KDAddKeywordViewDelegate
- (void)KDAddKeywordView:(KDAddKeywordView *)nameView DidSelectWithType:(NSInteger)type{
    self.hidesBottomBarWhenPushed = YES;

    KDWebBlockEditController *namevc = [[KDWebBlockEditController alloc]init];
    namevc.delegate = self;
    namevc.settingCellModel = self.model;
    [self.navigationController pushViewController:namevc animated:YES];

}

#pragma mark - KDWebEditCellDelegate
/**
 *  删除按钮被点击了
 */
- (void)KDWebEditCell:(KDWebEditCell *)cell deleteBtnClickWithModel:(KDWebEditCellModel *)model{
    
    [self deleteBlockRequestWithModel:model];
//    if (self.infoArr.count == 0) {
//        return;
//    }
    
//    [self.tableView reloadData];
}

#pragma mark - KDWebBlockEditControllerDelegate
/**
 *  当编辑web控制器的添加按钮被点击了的时候会调用本方法
 */
- (void)editController:(KDWebBlockEditController *)editCtr finishedEditWithModel:(KDWebEditCellModel *)model{
     [self getWebBlockListRequest];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self getWebBlockListRequest];
}
@end
